from flask import render_template, current_app, g, abort, jsonify, request

from info import constants, db
from info.models import Category, News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")



# 点赞功能实现

@news_blu.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    """
    评论点赞/取消点赞
    1. 获取参数  profile      comment_id  action
    2. 判断参数  不能为空     不能为空    不能为空
    3  判断用户的操作为点赞还是取消点赞
    4. 操作comment_like表，将对应的comment_id和user_id添加/删除
    5. 返回响应
    :return:
    """
    # 1.    获取参数    profile    comment_id    action
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    # 2.    判断参数    不能为空    不能为空    不能为空
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")
    # 3.    判断用户的操作为点赞还是取消点赞
    if action == "add":
    # 4.    操作comment_like表，将对应的comment_id和user_id模型添加 / 删除
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like_module = CommentLike()
            comment_like_module.comment_id = comment_id
            comment_like_module.user_id = user.id
            comment.like_count += 1
            db.session.add(comment_like_module)
    else:
        comment_like_module = CommentLike.query.filter(CommentLike.comment_id==comment_id,CommentLike.user_id==user.id)
        # db.session.delete(comment_like_module)
        comment_like_module.delete()
        comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAEXIST)
    # 5.    返回响应
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    """
    1. 获取请求参数
    2. 判断参数
    3. 初始化一个评论模型，并赋值
    4. 返回结果
    :return:
    """
    # 评论功能后端实现
    # 1. 获取请求参数
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="未登录")
    news_id = request.json.get("news_id")
    comment = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # 2. 判断参数
    if not all([news_id, comment]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="数据不存在")
    # 3. 初始化一个评论模型，并赋值
    comment_module = Comment()
    comment_module.user_id = user.id
    comment_module.news_id = news_id
    comment_module.content = comment
    if parent_id:
        comment_module.parent_id = parent_id
    db.session.add(comment_module)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库保存失败")
    # 4. 返回结果
    data = comment_module.to_dict()
    return jsonify(errno=RET.OK, errmsg="评论成功", data=data)




@news_blu.route("/news_collect", methods=["POST"])
@user_login_data
def collect_news():
    """
    收藏新闻
    1. 接收参数
    2. 判断参数
    3. 查询新闻并判断新闻是否存在
    :return:
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    # 1. 接收参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 2. 判断参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3. 查询新闻并判断新闻是否存在
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    # 4. 收藏
    if action == "cancel_collect":
        if news in user.collection_news:
            user.collection_news.remove(news)
    else:
        if news not in user.collection_news:
            # 代表用户未收藏将新闻添加到用户的收藏列表
            user.collection_news.append(news)
    return jsonify(errno=RET.OK, errmsg="操作成功")




@news_blu.route("/<int:news_id>")
@user_login_data
def news_detail(news_id):
    user = g.user
    # # 取出新闻
    # news_li = News.query().order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)
    if not news:
        abort(404)
    news.user = None
    try:
        category_li = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    category_dict_li = []
    for category in category_li:
        category_dict_li.append(category.to_dict())

    # 添加用户是否收藏功能
    # 默认未收藏
    is_collected = False
    # 判断用户是否登录
    # if user:
    #     # 代表用户已登录
    #     # 判断用户是否收藏该新闻
    #     if news in user.collection_news:
    #         # 代表用户收藏了该新闻
    #         is_collected = True
    # 从数据库中查询评论并返回
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id==news.id).\
            order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
    comment_dict_li = []

    # 当前页面评论是否被当前登录用户点赞逻辑实现
    # 获取到当前页面的所有评论id列表
    comment_ids = [comment.id for comment in comments]
    # 获取到当前用户的所有在本页面点赞的评论id
    comment_like_ids = []
    if user:
        try:
            comment_like_modules = CommentLike.query.filter(CommentLike.user_id==user.id,
                                                           CommentLike.comment_id.in_(comment_ids)).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        for comment_like in comment_like_modules:
            comment_like_ids.append((comment_like.comment_id))
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if comment.id in comment_like_ids:
            comment_dict["is_like"] = True
        comment_dict_li.append(comment_dict)
    # 根据点赞的评论id不同设置不同的

    # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # 判断用户是否收藏过该新闻
    is_collected = False
    if user:
        if news in g.user.collection_news:
            is_collected = True
        # if news.user.followers.filter(User.id == user.id).count() > 0:
        if news.user_id:
            if User.query.get(news.user_id).followers.filter(User.id==user.id).count() > 0:
                is_followed = True

    data = {
        "is_followed": is_followed,
        "user_dict": user.to_dict() if user else None,
        "news": news.to_dict(),
        "categories": category_dict_li,
        "news_dict_li": news_dict_li,
        "is_collected": is_collected,
        "comments": comment_dict_li,
    }
    return render_template("news/detail.html", data=data)
